<?php

class WSB_Validator_UniqueFeuser extends Zend_Validate_Abstract
{

	const USERNAME_EXISTS = 'uniqueFeuserUsernameExists';
	const EMAIL_EXISTS = 'uniqueFeuserEmailExists';

	const MODE_USER = 'user';
	const MODE_EMAIL = 'email';

	/**
	 * @var string
	 */
	private $_mode;

	/**
	 * @var array
	 */
    protected $_messageTemplates = array(
        self::USERNAME_EXISTS => "'%value%' already exists. Please choose another username.",
        self::EMAIL_EXISTS => "'%value%' already exists. Please choose another e-mail."
    );

    /**
     * @param string $mode
     */
    public function __construct($mode=self::MODE_USER)
	{
		$this->_mode = $mode;
    }

    /**
     * @param string $value
     * @return boolean
     */
    public function isValid($value)
    {
    	$value = trim($value);
        $this->_setValue($value);
        if (!empty($value)) {
	    	$table = new Member_Model_DbTable_Feuser();
	    	$select = $table->select();
	    	$select->where('deleted=?', 0);
	    	if($this->_mode == self::MODE_USER) {
	    		$select->where('username=?', $value);
	    	} else {
	    		$select->where('email=?', $value);
	    	}
	    	$item = $table->fetchRow($select);
	    	if($item instanceof Member_Model_DbTable_Feuser_Row) {
				if($this->_mode == self::MODE_USER) {
	    			$this->_error(self::USERNAME_EXISTS);
		    	} else {
	    			$this->_error(self::EMAIL_EXISTS);
		    	}
	            return false;
	    	}
        }
        return true;
    }
}
